/*
 * EventHandler.h
 *
 *  Created on: Oct 25, 2012
 *      Author: root
 */

#ifndef EVENTHANDLER_H_
#define EVENTHANDLER_H_

#include "IEventListener.h"

class EventHandler
{
	typedef void (*InternalFunction)(IEventListener *);


public:
	template <class C,void (C::*Func)()> static EventHandler * construct(C* inst)
	{
		EventHandler *handler = new EventHandler();
		handler->bind<C,Func>(inst);
		return handler;
	}
	
	template <class C, void (C::*Func)()> void bind(C* inst)
	{
		//function = &classMethod<C,Func>;
		function = (static_cast<C*>(inst)->*Func);
		instance = inst;
		Serial.print("BINDED TO INSTANCE");
	}

	
	void invoke()
	{
		if (function)
		{
			//Serial.println("INVOKING");
			if (instance)
			{
				Serial.println("INSTANCE EXISTS.");
				//function(instance);
			}
			
		}
	}



	template <class C, void(C::*Func)()> static inline void classMethod(IEventListener * inst)
	{
		Serial.println("classmethod");
		(static_cast<C*>(inst)->*Func)();
		
		//return ((inst)->*Func)();
	}



private:
	InternalFunction function;
	IEventListener *instance;
	EventHandler() {};
};
#endif /* EVENTHANDLER_H_ */
